#!/bin/bash

if [ `id -u` -ge 1000 ];then
  echo "usage: sudo bash $0 args..."
  exit 1
fi

# runDockerService(){
#   docker run --name "$name"
# }

# # aria
# name="aria.server.lan"
# docker run

# # gitea
# name="git.server.lan"

# # seafile
# name="seafile.server.lan"

# # bitwarden
# name="bitwarden.server.lan"


## timezone
if [ -z "$TZ" ];then
  tz="`grep -Eo "[^ ]+" /etc/timezone`"
  if [ -n "$tz" ];then
    export TZ="$tz"
  else
    echo "[Err] please set env TZ !!! eg. export TZ=Asia/Shanghai"
    echo 'echo "$TZ" > /etc/timezone'
    # -f == force
    echo 'ln -fs /usr/share/zoneinfo/$TZ /etc/localtime'
    exit 1
  fi
fi

echo "[INFO] env TZ=$TZ"


errflag=false
if [ ! -e "/usr/share/zoneinfo/$TZ" ];then
  echo "[Err] /usr/share/zoneinfo/$TZ : not exist"
  errflag=true
fi

if [ "x$(cat /etc/timezone)" != "x$TZ" ];then
  echo "[Err] /etc/timezone != \$TZ ($TZ) "
  errflag=true
fi

if $errflag ;then
  exit 1
fi


## run scripts
(
  cd "`dirname "$0"`"
  errfile=()
  errcount=0
  for i in ./*/install.sh;do
    if [ -f "$i" ];then
      echo "[info] run $i"
      if bash $i;then
        echo "[INFO] OK"
      else
        echo "[Err] error"
        errfile[$errcount]="$i"
        let errcount++
      fi
      echo "   ## "
    fi
  done

  flagErrCount=false
  for i in `seq 0 ${#errfile[@]}`;do
    if [ -z "${errfile[$i]}" ];then
      continue
    fi

    if [ $i -eq 0 ];then
        flagErrCount=true
        echo "[ERR] list errors : "
    fi
    echo "    - [ERR] :: ${errfile[$i]}"
  done

  runCMD(){
    echo "[INFO]::`date`::$1"
    if [ -f "$1" ];then
      bash "$1"
    else
      echo "[Err] can't find file :: $1"
    fi
    echo ""
  }

  postRUN(){
    local tmp=(
      "./postrun.set_email.sh" 
      "./postx.other.sh"
    )
    local cmd=""
    for i in `seq 0 ${#tmp[@]}`;do
      cmd="${tmp[$i]}"
      if [ -n "$cmd" ];then
        if ! $flagErrCount;then
          runCMD "$cmd"
        else
          echo "[Warn] need to run :: $cmd"
        fi
      fi
      
    done
  }

  ##  如果只是 恢复docker容器不要往下执行;if first intall . run 
  ### :
  # postRUN

)


